var msgList = [];
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;
var combinedResponse = '';
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'


const sparkConfigModule = require('./spark.config.js');
// 星火 API 相关配置,由于是隐私配置，可以自己构造模块或者直接把值填入
const sparkConfig = {
  httpUrl: sparkConfigModule.httpUrl,
  modelDomain: sparkConfigModule.modelDomain,
  APPID: sparkConfigModule.APPID,
  APIKey: sparkConfigModule.APIKey,
  APISecret: sparkConfigModule.APISecret
};

/**
 * 初始化数据
 */
function initData(that) {
  msgList = [{
    speaker: 'server',
    contentType: 'text',
    content: 'Hi，亲爱的同学，终于等到您啦！欢迎来到职场助手，很荣幸为您服务。' //
  },
  ];
  that.setData({
    msgList,
  });
}

Page({
  firstMessageSent: false, //新增会话标识
  openSlider: function () {
    if (this.data.open) {
      this.setData({
        open: false
      });
    } else {
      this.setData({
        open: true
      });
    }
  },
  tap_start: function (e) {
    // touchstart事件
    // 把手指触摸屏幕的那一个点的 x 轴坐标赋值给 mark 和 newmark
    this.data.mark = this.data.newmark = e.touches[0].pageX;
  },
  tap_drag: function (e) {
    // touchmove事件
    this.data.newmark = e.touches[0].pageX;
    // 手指从左向右移动
    if (this.data.mark < this.data.newmark) {
      this.istoright = true;
    }
    // 手指从右向左移动
    if (this.data.mark > this.data.newmark) {
      this.istoright = false;
    }
    this.data.mark = this.data.newmark;
  },
  tap_end: function () {
    // touchend事件
    this.data.mark = 0;
    this.data.newmark = 0;
    // 通过改变 opne 的值，让主页加上滑动的样式
    if (this.istoright) {
      this.setData({
        open: true
      });
    } else {
      this.setData({
        open: false
      });
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    isSending: false, // 助手回复状态变量
    //列表数据
    token: '',
    list: [{
      sessionId: 10,
      title: 'Hi，亲爱的同学，终于等到您啦！欢迎来到职场助手，很荣幸为您服务。',
      selected: false
    },
    {
      sessionId: 20,
      title: 'test2',
      selected: false
    },
    {
      sessionId: 30,
      title: 'test3',
      selected: false
    },
    {
      sessionId: 40,
      title: 'test4',
      selected: false
    },
    {
      sessionId: 50,
      title: 'test5',
      selected: false
    }
    ], //列表数据
    scrollHeight: '100vh',
    inputBottom: 0,
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    token: '',
    hasUserInfo: false
  },
  //历史对话背景颜色变换
  itemClick: function (e) {
    console.log("itemClick触发")
    const index = e.currentTarget.dataset.index;
    console.log('Clicked item:', index);
    const sessionId = this.data.list[index].sessionId;
    wx.request({
      url: `http://localhost:8080/chat/getconversation/${sessionId}`, // 后端获取对话消息接口
      method: 'GET',
      header: {
        'token': this.data.token // 根据后端要求设置前缀
      },
      success: (res) => {
        if (res.data.code === 1) {
          const conversationData = res.data.data; // 假设后端返回对话数据
          console.log(conversationData)
          let newMsgList = [];
          conversationData.forEach(record => {
            if (record.userMessage) {
              newMsgList.push({
                speaker: 'customer',
                contentType: 'text',
                content: record.userMessage
              });
            }
            if (record.serverMessage) {
              newMsgList.push({
                speaker: 'server',
                contentType: 'text',
                content: record.serverMessage
              });
            }
          });

          // 更新消息列表和界面
          msgList = newMsgList;
          this.setData({
            msgList
          });

          // 更新历史会话选中状态
          const updatedList = this.data.list.map((item, idx) => {
            return idx === index ? { ...item, selected: true } : { ...item, selected: false };
          });
          this.setData({
            list: updatedList
          });
          // 重置 firstMessageSent 标志，表示当前会话已经存在
          this.setData({
            firstMessageSent: true
          });
        } else {
          wx.showToast({
            title: res.data.msg || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  //历史对话背景颜色变换
  //删除列表
  delete: function (e) {
    console.log("delete触发")
    const index = e.currentTarget.dataset.index;
    const isSelected = this.data.list[index].selected;
    console.log('Delete item:', index);

    // 在这里添加删除逻辑
    if (index !== undefined) {
      const sessionId = this.data.list[index].sessionId;
      wx.request({
        url: `http://localhost:8080/chat/deletesession/${sessionId}`, // 后端删除会话接口
        method: 'DELETE',
        header: {
          'token': this.data.token // 根据后端要求设置前缀
        },
        success: (res) => {
          if (res.data.code === 1) {
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });

            // 更新前端列表
            const updatedList = this.data.list.filter((_, idx) => idx !== index);
            /*updatedList.forEach(item => {
              item.selected = false;
            });*/
            // 如果删除的是当前选中的会话，则调用 add() 方法清空界面
            if (isSelected) {
              this.add();
            }
            // 保持其他会话的选中状态不变
            this.setData({
              list: updatedList
            });
          } else {
            wx.showToast({
              title: res.data.msg || '删除失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
    }
  }, //删除列表
  //增加列表
  add() {
    // 清空当前对话内容
    msgList = [{
      speaker: 'server',
      contentType: 'text',
      content: 'Hi，亲爱的同学，终于等到您啦！欢迎来到职场助手，很荣幸为您服务。' //
    }]; // 只保留server的初始欢迎语
    this.setData({
      msgList,
      firstMessageSent: false
    });
    // 重置输入框
    this.data.list.forEach(element => {
      element.selected = false; //当点击添加对话时，列表选中状态消除
    })
    this.setData({
      inputVal: '',
      list: this.data.list
    });
  },
  //增加列表
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(sparkConfig);
    this.setData({
      firstMessageSent: false,
      //使用decodeURIComponent对encodeURIComponent()编码后的数据进行解码
      token: decodeURIComponent(options.token),
      userInfo: {
        avatarUrl: decodeURIComponent(options.avatarUrl),
        nickName: decodeURIComponent(options.nickName)
      }
    });
    this.loadSessionList();
    console.log("这是token令牌：" + this.data.token);
    console.log(this.data.userInfo.avatarUrl); // 获取传递的头像 URL
    console.log(options.nickName); // 获取传递的昵称
    initData(this);
  },
  // 加载历史会话列表
  loadSessionList: function () {
    wx.request({
      url: 'http://localhost:8080/chat/getsession', // 后端获取会话列表接口
      method: 'GET',
      header: {
        'token': this.data.token // 根据后端要求设置前缀
      },
      success: (res) => {
        if (res.data.code === 1) {
          console.log(res.data)
          const sessionList = res.data.data.map(session => {
            return {
              sessionId: session.sessionId,
              title: session.title,
              selected: false
            };
          });

          this.setData({
            list: sessionList
          });
        } else {
          wx.showToast({
            title: res.data.msg || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 页面卸载时
  onUnload() {
    if (this.socketTask) {
      this.socketTask.close();
    }
  },

  /**
   * 获取聚焦
   */
  focus: function (e) {
    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px',
      inputBottom: keyHeight + 'px'
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    });
  },

  // 失去聚焦(软键盘消失)
  blur: function () {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    });
  },

  /**
   * 发送点击监听
   */
  inputChange(e) {
    this.setData({
      inputVal: e.detail.value
    });
  },

  sendClick: function () {
    const userMessage = this.data.inputVal.trim();
    console.log(userMessage);
    if (!userMessage) return;
    if (this.data.isSending) {
      return;
    }
    this.setData({
      isSending: true
    });
    // 如果是第一次发送消息，将消息添加到历史会话列表
    if (!this.data.firstMessageSent) { // 如果是第一次发送消息
      wx.request({
        url: 'http://localhost:8080/chat/addsession', // 后端创建会话接口
        method: 'POST',
        header: {
          'token': this.data.token, // 根据后端要求设置前缀
          'title': encodeURIComponent(userMessage)
        },
        data: {
        },
        success: (res) => {
          if (res.data.code === 1) {
            console.log(res.data.data.sessionId);
            const sessionId = res.data.data.sessionId; // 获取后端返回的 sessionId
            // 创建新会话对象并添加到列表
            const newSession = {
              sessionId: sessionId,
              title: userMessage,
              selected: true
            };
            console.log(newSession);
            this.data.list.push(newSession);
            this.setData({
              list: this.data.list
            });

            this.setData({
              firstMessageSent: true
            });
          } else {
            wx.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            });
          }
          console.log(res);
        },
        fail: () => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
    }
    // 添加用户消息到消息列表
    const customerMsg = {
      speaker: 'customer',
      contentType: 'text',
      content: userMessage
    };
    msgList.push(customerMsg);

    // 更新输入框和消息列表
    this.setData({
      msgList,
      inputVal: ''
    });

    // 调用星火 API 获取回复
    this.getSparkResponse().then(() => {
      // 获取最新一条用户消息和服务器消息
      const userMsg = msgList.findLast(msg => msg.speaker === 'customer');
      const serverMsg = msgList.findLast(msg => msg.speaker === 'server');

      if (userMsg && serverMsg && this.data.firstMessageSent) {
        const sessionId = this.data.list.find(item => item.selected === true)?.sessionId;

        wx.request({
          url: 'http://localhost:8080/chat/addconversation', // 后端存储对话接口
          method: 'POST',
          header: {
            'token': this.data.token // 根据后端要求设置前缀
          },
          data: {
            sessionId: sessionId,
            userMessage: userMsg.content,
            serverMessage: serverMsg.content
          },
          success: (res) => {
            if (res.data.code !== 1) {
              wx.showToast({
                title: res.data.msg || '存储失败',
                icon: 'none'
              });
            }
          },
          fail: () => {
            wx.showToast({
              title: '网络请求失败',
              icon: 'none'
            });
          }
        });
      }

      this.setData({
        isSending: false
      });
    });
  },
  /**
   * 获取星火 API 的回复
   */
  getSparkResponse() {
    return new Promise((resolve, reject) => { // 返回一个Promise
      const _this = this;

      // 构建带上下文的请求参数
      const textMessages = [
        {
          role: "system",
          content: "你是一个专业的职场助手，帮助用户解答求职面试、职业发展、职场沟通等问题。请保持回答的专业性和实用性，同时使用自然的口语化表达。"
        }
      ];

      // 将历史对话转换为API需要的格式
      msgList.forEach(msg => {
        if (msg.speaker === 'customer') {
          textMessages.push({ role: "user", content: msg.content });
        } else if (msg.speaker === 'server') {
          textMessages.push({ role: "assistant", content: msg.content });
        }
      });

      const params = {
        header: {
          app_id: sparkConfig.APPID
        },
        parameter: {
          chat: {
            domain: sparkConfig.modelDomain,
            temperature: 0.5,
            max_tokens: 4096
          }
        },
        payload: {
          message: {
            text: textMessages  // 包含上下文信息的消息数组
          }
        }
      };

      // 获取 WebSocket URL
      this.getWebSocketUrl().then(url => {
        // 建立 WebSocket 连接
        _this.socketTask = wx.connectSocket({
          url: url,
          method: 'GET',
          success: function (res) {
            console.log('WebSocket 连接成功', res);
          },
          fail: function (res) {
            console.log('WebSocket 连接失败', res);
            reject(new Error('WebSocket 连接失败')); // 拒绝Promise
          }
        });

        // 监听 WebSocket 错误
        _this.socketTask.onError(function (res) {
          console.log('WebSocket 发生错误', res);
          reject(new Error('WebSocket 发生错误')); // 拒绝Promise
        });

        // 监听 WebSocket 打开
        _this.socketTask.onOpen(function (res) {
          console.log('WebSocket 已打开', res);
          // 发送消息
          _this.socketTask.send({
            data: JSON.stringify(params),
            success: function () {
              console.log('消息发送成功');
            },
            fail: function (err) {
              console.log('消息发送失败', err);
              reject(new Error('消息发送失败')); // 拒绝Promise
            }
          });
        });

        // 监听 WebSocket 消息
        _this.socketTask.onMessage(function (res) {
          const data = JSON.parse(res.data);
          if (data.header.code === 0 && data.payload.choices) {
            const botResponses = data.payload.choices.text;


            // 合并多段回复
            botResponses.forEach(response => {
              combinedResponse += response.content;
            });
          } else {
            console.log('星火 API 返回错误', data);
            reject(new Error('星火 API 返回错误')); // 拒绝Promise
          }

          // 关闭 WebSocket 连接
          //_this.socketTask.close();
        });

        // 监听 WebSocket 关闭
        _this.socketTask.onClose(function (res) {
          console.log(res.code);
          console.log('WebSocket 已关闭', res);
          // 如果 WebSocket 关闭时还没有重置状态，则重置状态
          if (_this.data.isSending) {
            _this.setData({
              isSending: false
            });
          }
          if (res.code !== 1000) {
            reject(new Error('WebSocket 连接异常关闭')); // 拒绝Promise
          } else {
            const botMsg = {
              speaker: 'server',
              contentType: 'text',
              content: combinedResponse
            };
            console.log(botMsg);
            msgList.push(botMsg);
            _this.setData({
              msgList
            });
            resolve();
          }
          combinedResponse = '';
        });
      }).catch(err => {
        console.log('获取 WebSocket URL 失败', err);
        reject(new Error('获取 WebSocket URL 失败')); // 拒绝Promise
      });
    });
  },

  //接口函数

  //接口函数

  /**
   * 获取 WebSocket URL
   */
  getWebSocketUrl() {
    const httpUrlHost = sparkConfig.httpUrl.substring(8, 28);
    const httpUrlPath = sparkConfig.httpUrl.substring(28);

    switch (httpUrlPath) {
      case "/v1.1/chat":
        sparkConfig.modelDomain = "lite";
        break;
      case "/v2.1/chat":
        sparkConfig.modelDomain = "generalv2";
        break;
      case "/v3.1/chat":
        sparkConfig.modelDomain = "generalv3";
        break;
      case "/v3.5/chat":
        sparkConfig.modelDomain = "generalv3.5";
        break;
    }

    return new Promise((resolve) => {
      const CryptoJS = require('crypto-js');
      const Base64 = require('base-64');
      const url = `wss://${httpUrlHost}${httpUrlPath}`;
      const host = "spark-api.xf-yun.com";
      const apiKeyName = "api_key";
      const date = new Date().toGMTString();
      const algorithm = "hmac-sha256";
      const headers = "host date request-line";
      const signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrlPath} HTTP/1.1`;

      // 使用 CryptoJS 计算 HMAC-SHA256 签名
      const signature = CryptoJS.HmacSHA256(signatureOrigin, sparkConfig.APISecret).toString(CryptoJS.enc.Base64);

      const authorizationOrigin = `${apiKeyName}="${sparkConfig.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
      const authorization = Base64.encode(authorizationOrigin);
      const finalUrl = `${url}?authorization=${authorization}&date=${encodeURIComponent(date)}&host=${host}`;
      resolve(finalUrl);
    });
  }
});